package pro.softzhang.algo.lc0;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

public class LC56_MergeIntervals {
    public static void main(String[] args) {

    }

    static class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals, Comparator.comparingInt(a -> a[0]));

            List<int[]> merged = new ArrayList<>();
            int i = 0;
            while (i < intervals.length) {
                int[] tmp = new int[]{intervals[i][0], intervals[i][1]};
                int j = i + 1;
                while (j < intervals.length && intervals[j][0] <= tmp[1]) {
                    tmp[1] = Math.max(tmp[1], intervals[j][1]);
                    j++;
                }
                merged.add(tmp);
                i = j;
            }

            int[][] result = new int[merged.size()][];
            return merged.toArray(result);
        }
    }
}
